import { createStore } from 'vuex'
import axios from 'axios'

const store = createStore({
  state: {
    activeSession: null,
    signInRecords: [],
    websocket: null,
    isConnected: false,
    signInStatus: {
      success: false,
      message: ''
    },
    historicalSessions: []
  },
  mutations: {
    SET_ACTIVE_SESSION(state, session) {
      state.activeSession = session
    },
    SET_SIGN_IN_RECORDS(state, records) {
      state.signInRecords = records
    },
    ADD_SIGN_IN_RECORD(state, record) {
      state.signInRecords.push(record)
    },
    SET_HISTORICAL_SESSIONS(state, sessions) {
      state.historicalSessions = sessions
    },
    SET_WEBSOCKET(state, ws) {
      state.websocket = ws
    },
    SET_CONNECTED(state, isConnected) {
      state.isConnected = isConnected
    },
    SET_SIGN_IN_STATUS(state, status) {
      state.signInStatus = status
    },
    CLEAR_SIGN_IN_STATUS(state) {
      state.signInStatus = { success: false, message: '' }
    }
  },
  actions: {
    // 初始化WebSocket连接
    initWebSocket({ commit, dispatch, state }) {
      // 防止重复初始化WebSocket连接
      if (state.websocket && (state.websocket.readyState === WebSocket.OPEN || state.websocket.readyState === WebSocket.CONNECTING)) {
        console.log('WebSocket连接已存在，无需重复初始化')
        return
      }
      
      const ws = new WebSocket('ws://192.168.12.106:9999/ws')
      
      ws.onopen = () => {
        console.log('WebSocket连接已建立')
        commit('SET_CONNECTED', true)
        // 连接成功后查询活动会话
        dispatch('queryActiveSession')
      }
      
      ws.onmessage = (event) => {
        const data = JSON.parse(event.data)
        console.log('收到WebSocket消息:', data)
        
        switch (data.type) {
          case 'activeSession':
            commit('SET_ACTIVE_SESSION', data.session)
            // 签到记录已经在后端查询并返回，不需要再次查询
            break
          case 'signInRecords':
            commit('SET_SIGN_IN_RECORDS', data.records)
            break
          case 'newSignInRecord':
            // 获取当前活动会话的教室，或使用targetClassroom判断
            const currentClassroom = state.activeSession?.classroom;
            const targetClassroom = data.targetClassroom || data.classroomLocation;
            
            // 只有当签到记录的教室与当前活动会话的教室匹配时才更新记录
            // 这样不同教室的教师只会收到自己教室的签到信息
            if (!currentClassroom || targetClassroom === currentClassroom) {
                commit('ADD_SIGN_IN_RECORD', {
                studentName: data.studentName,
                classroomLocation: data.classroomLocation,
                signInTime: new Date()
                })
            }
            break
          case 'signInResult':
            commit('SET_SIGN_IN_STATUS', {
              success: data.success,
              message: data.message
            })
            break
          case 'signInSessionActive':
          case 'signInSessionEnded':
            // 获取广播消息中的教室信息
            const broadcastClassroom = data.classroom;
            
            // 学生端处理逻辑：当学生已经选择了教室时，只有消息中的教室与学生选择的教室匹配才更新
            if (window.currentSelectedClassroom) {
              if (!broadcastClassroom || broadcastClassroom === window.currentSelectedClassroom) {
                dispatch('queryActiveSessionByClassroom', window.currentSelectedClassroom)
              }
            }
            
            // 教师端处理逻辑：如果当前有活动会话，只有消息中的教室与教师当前教室匹配才更新
            if (state.activeSession) {
              const currentClassroom = state.activeSession.classroom;
              // 如果广播消息没有教室信息（兼容旧版本），或者教室信息匹配，则更新
              if (!broadcastClassroom || broadcastClassroom === currentClassroom) {
                if (currentClassroom) {
                  dispatch('queryActiveSessionByClassroom', currentClassroom);
                } else {
                  dispatch('queryActiveSession');
                }
              }
            }
            break
        }
      }
      
      ws.onclose = () => {
        console.log('WebSocket连接已关闭')
        commit('SET_CONNECTED', false)
        // 重连逻辑
        setTimeout(() => {
          dispatch('initWebSocket')
        }, 5000)
      }
      
      commit('SET_WEBSOCKET', ws)
    },
    
    // 发送WebSocket消息
    sendWebSocketMessage({ state }, message) {
      if (state.websocket && state.isConnected && state.websocket.readyState === WebSocket.OPEN) {
        state.websocket.send(JSON.stringify(message))
      } else if (state.websocket && state.websocket.readyState === WebSocket.CONNECTING) {
        // 如果正在连接中，等待连接建立后再发送
        const waitForConnection = () => {
          if (state.websocket.readyState === WebSocket.OPEN) {
            state.websocket.send(JSON.stringify(message))
          } else if (state.websocket.readyState !== WebSocket.CLOSED) {
            setTimeout(waitForConnection, 100)
          }
        }
        waitForConnection()
      }
    },
    
    // 查询活动会话
    queryActiveSession({ dispatch }) {
      dispatch('sendWebSocketMessage', { type: 'queryActiveSession' })
    },
    
    // 按教室查询活动会话
    queryActiveSessionByClassroom({ dispatch }, classroom) {
      dispatch('sendWebSocketMessage', { 
        type: 'queryActiveSessionByClassroom',
        classroom: classroom
      })
    },
    
    // 查询签到记录
    querySignInRecords({ dispatch }, sessionId) {
      dispatch('sendWebSocketMessage', {
        type: 'querySignInRecords',
        sessionId: sessionId
      })
    },
    // 查询历史签到会话
    async queryHistoricalSessions({ commit }, params) {
      try {
        const response = await axios.get('/api/sign-in/history', { params })
        // 假设后端返回的数据格式为 { data: [], total: number }
        // 如果是直接返回数组，则适配为分页格式
        if (Array.isArray(response.data)) {
          commit('SET_HISTORICAL_SESSIONS', response.data)
          return { data: response.data, total: response.data.length }
        } else {
          // 如果已经是分页格式，提取data字段
          commit('SET_HISTORICAL_SESSIONS', response.data.data || [])
          return response.data
        }
      } catch (error) {
        console.error('查询历史签到会话失败:', error)
        throw error
      }
    },
    // 获取历史签到记录
    async getHistoricalSessionRecords({ commit }, sessionId) {
      try {
        const response = await axios.get(`/api/sign-in/sessions/${sessionId}/records`)
        commit('SET_SIGN_IN_RECORDS', response.data)
      } catch (error) {
        console.error('获取历史签到记录失败:', error)
        throw error
      }
    },
    
    // 开始签到
    startSignIn({ dispatch, state }) {
      if (!state.activeSession) return;
      
      dispatch('sendWebSocketMessage', {
        type: 'startSignIn',
        sessionId: state.activeSession.id
      })
      
      // 发送消息后，重新查询活动会话状态
      setTimeout(() => {
        if (state.activeSession) {
          const classroom = state.activeSession.classroom;
          if (classroom) {
            dispatch('queryActiveSessionByClassroom', classroom);
          } else {
            dispatch('queryActiveSession');
          }
        }
      }, 500); // 延迟查询，确保后端有足够时间处理请求
    },
    
    // 结束签到
    endSignIn({ dispatch, state }) {
      if (!state.activeSession) return;
      
      dispatch('sendWebSocketMessage', {
        type: 'endSignIn',
        sessionId: state.activeSession.id
      })
      
      // 发送消息后，重新查询活动会话状态
      setTimeout(() => {
        if (state.activeSession) {
          const classroom = state.activeSession.classroom;
          if (classroom) {
            dispatch('queryActiveSessionByClassroom', classroom);
          } else {
            dispatch('queryActiveSession');
          }
        }
      }, 500); // 延迟查询，确保后端有足够时间处理请求
    },
    
    // 学生签到
    studentSignIn({ dispatch }, { sessionId, data }) {
      dispatch('sendWebSocketMessage', {
        type: 'studentSignIn',
        sessionId: sessionId,
        data: data
      })
    },
    
    // 创建签到会话（REST API）
    async createSignInSession({ commit }, sessionData) {
      try {
        const response = await axios.post('/api/sign-in/sessions', sessionData)
        // 将创建的会话数据提交到state中，更新activeSession
        commit('SET_ACTIVE_SESSION', response.data)
        return response.data
      } catch (error) {
        console.error('创建签到会话失败:', error)
        throw error
      }
    },
    
    // 踢出签到学生
    async kickOutStudent({ dispatch, state }, studentName) {
      try {
        const sessionId = state.activeSession?.id;
        if (!sessionId) {
          throw new Error('没有活动的签到会话');
        }
        
        const response = await axios.delete(`/api/sign-in/sessions/${sessionId}/records`, {
          params: { studentName }
        });
        
        // 踢出成功后刷新签到记录
        if (response.data.success) {
          dispatch('querySignInRecords', sessionId);
        }
        
        return response.data;
      } catch (error) {
        console.error('踢出学生失败:', error);
        throw error;
      }
    }
  },
  getters: {
    hasActiveSession: state => !!state.activeSession,
    isSignInInProgress: state => state.activeSession?.status === 1,
    signInRecordCount: state => state.signInRecords.length
  }
})

export default store